import qs from 'qs';
import { storage } from '@/tools/storage.js';
import encrypt from '@/tools/encrypt';
import { router } from '@/tools/router';
import { Toast } from '@/tools/util';

// 登录token失效错误码
const errorCode = [40001, 40002, 40003, 40004, 40008, 20007, 50007, 20008];

// 设置请求头
const setHeader = (url) => {
    let header = {
        "Content-Type": "application/json;charset=utf-8",
        "Access-Control-Allow-Origin": "*"
    };
    let token = storage.get('token');
    if (token) {
        header.token = token;
    }
    return header;
};

// 设置请求参数
const setParams = (params) => {
    return params;
    // return qs.stringify(params);
};

/*
 * http请求实例
 * method 请求方式：post/get
 * url 请求url
 * params 请求参数
 * showErrorMessage 接口请求失败时是否吐司提示错误信息
*/
const http = (method, url, params, showErrorMessage) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: url,
            data: setParams(params),
            header: setHeader(url),
            method: method,
            timeout: 30000
        }).then(async (res) => {
            if (res.statusCode == 200) {
                if (errorCode.indexOf(res.data.code) == -1) {
                    resolve(res.data.data);
                } else {
                    // toast提示接口报错信息
                    if (showErrorMessage) {
                        Toast(res.data.msg);
                    }
                    // 清除登录状态相关缓存
                    storage.clear();
                    // 登录失效，返回登录页面
                    setTimeout(() => {
                        router.go('/pages/Login/Login', 'reLaunch');
                    }, 1500);
                }
            } else {
                reject(res.data);
                Toast('当前网络不给力哦~');
            }
        }).catch((err) => {
            reject(err);
        });
    });
};

const request = {
    get: (url, params, showErrorMessage = true) => {
        return http('GET', url, params, showErrorMessage);
    },
    post: (url, params, showErrorMessage = true) => {
        return http('POST', url, params, showErrorMessage);
    },
    interceptors: () => {
        // 拦截器
        const apiList = ['request', 'uploadFile'];
        apiList.forEach(item => {
            uni.addInterceptor(item, {
                invoke: async (config) => {
                    // 调用前拦截，可以在这里对config进行处理
                    return config;
                },
                returnValue: (res) => {
                    // 调用后拦截
                    // console.log(res, 111);
                    return res;
                },
                success: (e) => {
                    // console.log('interceptor-success', e);
                },
                fail: (err) => {
                    // console.log('interceptor-fail', err);
                }
            });
        });
    }
};

export default request;
